#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QPainter>
#include <QThread>
#include<thread>
#include"songlist2.h"
MainWindow::MainWindow(QString nameid, QString name, QString passwd,QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    m_nameid=nameid;
    m_name=name;
    m_passwd=passwd;
    isstart=true;

    inittitle();      //初始化标题
    initpushbutton(); //初始化按钮
    initnetwork();    //初始化网络

     DiscoverMusicModule();

     qRegisterMetaType<list<QString>>("list<QString>");
     lovemusicmodule();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::DiscoverMusicModule()
{
    connect(ui->faxian,&DiscoverMusicModule::playmusic,ui->playwidget,&MusicPlayBar::SendRequst);
    ui->faxian->setinfo(m_nameid,m_passwd);

    this->hintlabel=new QLabel(this);
    this->timer=new QTimer(this);

    // 设置文本对齐方式
    this->hintlabel->setAlignment(Qt::AlignCenter);
    this->hintlabel->setFixedSize(200,100);
    this->hintlabel->setStyleSheet("background-color:rgb(62, 62, 62);color:rgb(255, 255, 255);border-radius:10px;");
    this->hintlabel->move(width()/2-100,height()/2-130);
    this->hintlabel->hide();

    connect(ui->faxian,&DiscoverMusicModule::NotifyShow,this,[&](QString str1,QString str2){
         //"AddLoveMusic","success"
         //"AddLoveMusic","Failing");
         //"DelLoveMusic","success");
         //"DelLoveMusic","Failing");
         if(str1=="AddLoveMusic")
         {
            if(str2=="success")
            {
               hintlabel->setText("已添加到我喜欢的音乐");
            }
            else
            {
               hintlabel->setText("添加到我喜欢的音乐失败");
            }
         }
         else if(str1=="DelLoveMusic")
         {
             if(str2=="success")
             {
                hintlabel->setText("移除我喜欢的音乐");
             }
             else
             {
                hintlabel->setText("移除我喜欢的音乐失败");
             }
         }
         timer->start(1000);
         hintlabel->show();
    });

    connect(timer,&QTimer::timeout,this,[&](){
          timer->stop();
          hintlabel->hide();
    });
}

void MainWindow::GainUseLoveList(MainWindow *m,QString nameid, QString passwd)
{
    //获取用户喜欢列表
    //usrnameid:{1373474316}\r\npassword:{137347}\r\nGainUseLoveList:{}\r\n
    QString request;
    //usrnameid:{1373474316}\r\npassword:{137347}\r\nGainUseLoveList:{}\r\n
    request += QString("usrnameid:{%1}\\r\\n").arg(nameid);
    request += QString("password:{%1}\\r\\n").arg(passwd);
    request += QString("GainUseLoveList:{}\\r\\n");

    tcpclient*client=new tcpclient();
    client->write(request);
    client->send();
    while(1)
    {
        // 检查连接状态
        if (client->m_socket->state() == QAbstractSocket::UnconnectedState) {
            // 连接已关闭，跳出while循环
            break;
        }
        if(!client->m_socket->waitForReadyRead())
        {
            continue;
        }
        client->Receiving.append(client->m_socket->readAll());

    }
    QByteArray response=client->getnetworkdata();
    list<QString>musiclist;
    if(!response.isNull())   //不为空
    {
        int start = 0;
        int end = response.indexOf('\n'); // 查找第一个换行符的索引

        while (end != -1) {
            QByteArray lineData = response.mid(start, end - start);

            // 处理单行数据，例如输出到控制台
            musiclist.push_back(lineData);

            start = end + 1; // 更新下一行的起始位置
            end = response.indexOf('\n', start); // 查找下一个换行符的索引
        }
    }
    delete  client;
    client=nullptr;
     //发送信号
    emit m->showmusiclist(musiclist);
}


void MainWindow::inittitle()
{
    setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint);//去掉标题栏
    setFixedSize(1300,880);

    ui->titlebar->move(0,0);
    ui->titlebar->setFixedSize(1300,80);

    connect(ui->titlebar,&title::WindowMove,[=](QPoint p){
           move(x()+p.x(), y()+p.y());
    });

    connect(ui->titlebar,&title::myclose,[=](){
        close();
    });

    connect(ui->titlebar,&title::changewindow,[=](bool flag){
          Q_UNUSED(flag);
//        if(!flag){
//            this->setWindowState(Qt::WindowMaximized);
//        }
//        else{
//            this->setWindowState(Qt::WindowNoState);
//        }
    });

    connect(ui->titlebar,&title::Windowmin,[=](){
        // 将窗口最小化
        this->setWindowState(Qt::WindowMinimized);
    });


    //加载用户头像
    ui->touxiang->setScaledContents(true);
    ui->touxiang->setPixmap(QPixmap(":/new/prefix1/res/UserHeadPortrait.png"));
    ui->username->setText(m_name);

    //设置音乐播放窗口   1300 880

    ui->playwidget->setFixedSize(1300,100);
    ui->playwidget->move(0,780);

    ui->line->setFixedSize(1300,1);
    ui->line->move(0,779);

    ui->line_2->setFixedSize(20,700);
    ui->line_2->move(152,80);
}

void MainWindow::initpushbutton()
{
    QString normal("font: 12pt Microsoft PhagsPa");
    QString enter("font:  12pt Microsoft PhagsPa;"
                  "background-color: rgb(210, 210, 210);");
    QString chick("font:  12pt Microsoft PhagsPa;"
                  "background-color: rgb(210, 210, 210);");

    this->But<<ui->faxian_1<<ui->faxian_2<<ui->faxian_3
            <<ui->faxian_4<<ui->faxian_5<<ui->faxian_6
            <<ui->faxian_7<<ui->faxian_8<<ui->faxian_9;
    //图标1
    for(int i=0;i<6;i++)
    {
        this->But[i]->set(normal,enter,chick);
    }
    for(int i=6;i<9;i++)
    {
        if(i==6){
            this->But[i]->setIcon(QIcon(":/new/prefix1/res/love.png"));
            this->But[i]->setLayoutDirection(Qt::LeftToRight);
            this->But[i]->setText("我喜欢的音乐 ");
        }else if(i==7){
            this->But[i]->setIcon(QIcon(":/new/prefix1/res/xiazaitubiao.png"));
            this->But[i]->setLayoutDirection(Qt::LeftToRight);
            this->But[i]->setText("本地与下载    ");
        }
        else if(i==8){
            this->But[i]->setIcon(QIcon(":/new/prefix1/res/naozhong.png"));
            this->But[i]->setLayoutDirection(Qt::LeftToRight);
            this->But[i]->setText("最近播放       ");
        }
        //this->But[i]->move(x,y+i*41+40);
        //this->But[i]->setFlat(true);
        this->But[i]->set(normal,enter,chick);

    }
    ui->funtionwidget->setCurrentIndex(0);
    ui->funtionwidget->move(165,80);
    ui->funtionwidget->setFixedHeight(699);
    for(int i=0;i<this->But.size();i++){
        //注册按下信号
        connect(this->But[i],&MyButton::clicked,this,[=](){
             MyButton* btn = (MyButton*)sender();
             for(int i=0;i<this->But.size();i++)
             {
                 if(btn==But[i])
                 {
                     But[i]->setfalg(true);
                     ui->funtionwidget->setCurrentIndex(i);  //切换窗口
                 }
                 else
                 {
                     But[i]->setfalg(false);
                 }
                 But[i]->mypress();
             }
        });
    }

}

void MainWindow::initnetwork()
{
    //client=new tcpclient();
}


void MainWindow::lovemusicmodule()
{
    //ui->love_scrollArea->setFixedHeight(460);

    //QRect(50,250 1091x460)
    //ui->love_scrollArea->widget()->setMinimumSize(1091,460);
    //ui->love_scrollArea->widget()->setMaximumSize(1091,460);
    connect(this,&MainWindow::showmusiclist,this,&MainWindow::showlist);
}

void MainWindow::showlist(list<QString> lis)
{
    int index=1;
    if(m_pLayout==nullptr)
    {
       m_pLayout=new QVBoxLayout(nullptr);
    }
    else
    {
        QLayoutItem* item;
        while ((item = m_pLayout->takeAt(0)) != nullptr)
        {
            delete item->widget();
            delete item;
        }
        delete  m_pLayout;
        m_pLayout=nullptr;
        m_pLayout=new QVBoxLayout(nullptr);

    }
    ui->love_scrollArea->setFixedSize(1091,460);
    while(!lis.empty())
    {
        QString front=lis.front();
        MusicInfo *info=new MusicInfo(true,index,front,"无","无","无",nullptr);
        connect(info,&MusicInfo::addlove,ui->faxian,&DiscoverMusicModule::addlovemusic);
        connect(info,&MusicInfo::dellove,ui->faxian,&DiscoverMusicModule::dellovemusic);
        m_pLayout->addWidget(info);
        lis.pop_front();
        connect(info,&MusicInfo::doubleClicked,this,[&](tcpclient*client,QString title){
             emit ui->faxian->playmusic(client,title);
        });
        index++;
    }

    if(index<50)   // 占位
    {
        for(int i=0;i<10;i++)
        {
            QWidget*w=new QWidget();
            m_pLayout->addWidget(w);
        }
    }
    ui->love_scrollArea->setWidgetResizable(true);
    ui->love_scrollArea->setLayout(m_pLayout);
    update();
}


void MainWindow::on_SerachButton_clicked()
{
     qDebug()<<ui->SerachlineEdit->text()<<endl;
}

void MainWindow::on_faxian_7_clicked()
{
    ui->love_usrname->setText(m_name);

    list<QString>musiclist;
    //启动线程接受数据
    std::thread *pa=new std::thread(GainUseLoveList,this,m_nameid,m_passwd);
    pa->detach();
}

void MainWindow::on_pushButton_clicked()
{
    delete m_pLayout; // 删除旧布局
    m_pLayout=nullptr;
    ui->funtionwidget->setCurrentIndex(0);
}
